package com.hxs.learn.aop;

import com.hxs.learn.common.result.Result;
import com.hxs.learn.common.web.utils.AjaxUtils;
import com.hxs.learn.web.ViewNames;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;


/**
 * @author huxinsheng
 */
@RestController
@RequestMapping("/error")
public class AdminErrorController implements ErrorController {

    private static final String PATH_404 = "/404";

    private static final String PATH_403 = "/403";

    private static final String PATH_500 = "/500";

    private static final String PATH_ERROR = "/error";

    @RequestMapping(value = PATH_404)
    public ModelAndView handle404() {
        return new ModelAndView(ViewNames.PAGE_404);
    }

    @RequestMapping(value = PATH_403)
    public ModelAndView handle403() {
        return new ModelAndView(ViewNames.PAGE_403);
    }

    @RequestMapping(value = PATH_500)
    @ResponseBody
    public ModelAndView handle500() {
        return new ModelAndView(ViewNames.PAGE_500);
    }

    @RequestMapping(value = PATH_ERROR)
    @ResponseBody
    public ModelAndView handleError(WebRequest request, HttpServletResponse response) {
        if (AjaxUtils.isAjaxRequest(request)) {
            //ajax 则返回json
            AjaxUtils.writeJson(Result.error(404, "地址不存在"), response);
            return null;
        }
        return new ModelAndView("_error/error");
    }

    @Override
    public String getErrorPath() {
        return PATH_500;
    }
}
